package models

import (
	"gintest/database"
	"time"
)

//表结构
type Delivery struct {
	Id        int    `json:"id" gorm:"column:id;primary_key" form:"id"`
	UserId  int `json:"user_id" gorm:"column:user_id" form:"user_id"`
	Name string `json:"name" gorm:"column:name" form:"name"`
	Phone string `json:"phone" gorm:"column:phone" form:"phone"`
	Address  string `json:"address" gorm:"column:address" form:"address"`
	Province  string `json:"province" gorm:"column:province" form:"province"`
	City string `json:"city" gorm:"column:city" form:"city"`
	Longitude string `json:"longitude" gorm:"column:longitude" form:"longitude"`
	Latitude string `json:"latitude" gorm:"column:latitude" form:"latitude"`
	CreateAt time.Time  `json:"create_at" gorm:"column:create_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"create_at"`
	UpdateAt time.Time  `json:"update_at" gorm:"column:update_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"update_at"`
	DeleteAt time.Time  `json:"delete_at" gorm:"column:delete_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"delete_at"`
}
func (Delivery) TableName() string {
	return "delivery"
}

func GetDeliveryList(page uint64,pagesize uint64,keyword string,user_id uint64)(data []Delivery,total uint64){
	var offset=(page-1)*pagesize
	db:=database.SqlDB.Model(Delivery{})

	if len(keyword)!=0{
		db=db.Where("concat(user_id,name,phone,city,province,address) like ?","%"+keyword+"%")
	}

	if user_id>0{
		db=db.Where("user_id = ?",user_id)
	}

	db=db.Where("delete_at = 0 or delete_at is null")

	db.Offset(offset).Limit(pagesize).Order("id desc").Find(&data)
	db.Model(Delivery{}).Count(&total)

	return data,total
}
func AddDelivery(data *Delivery) error{
	if data.UpdateAt.IsZero(){
		data.UpdateAt=time.Now()
	}
	if data.CreateAt.IsZero(){
		data.CreateAt=time.Now()
	}
	return database.SqlDB.Model(Delivery{}).Create(data).Error
}
func DelDeliveryByIds(ids []int) error{
	//return database.SqlDB.Model(Article{}).Where("id in (?)",ids).Delete(Article{}).Error
	return database.SqlDB.Model(Delivery{}).Where("id in (?) and (delete_at = 0 or delete_at is null)",ids).Update("delete_at",time.Now().Local().String()).Error
}
func GetDeliveryById(id int) (data Delivery){
	database.SqlDB.Model(Delivery{}).Where("id=?",id).First(&data);
	return data
}
/**
	更新
	id 编号
    data map[string]interface{}
*/
func EditDeliveryById(id int,data interface{}) error{
	//update_at不存在，填充当前时间
	if _, has := data.(map[string]interface{})["update_at"]; !has {
		data.(map[string]interface{})["update_at"]=time.Now()
	}
	return database.SqlDB.Model(&Delivery{}).Where("id=?",id).Updates(data).Error
}